package com.hzhr.iot.web.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.hzhr.iot.core.util.HzhrDateUtil;
import com.hzhr.iot.core.util.HzhrTypeUtil;
import com.hzhr.iot.device.sdk.model.implRecord.ImplRecordGetModel;
import com.hzhr.iot.device.sdk.model.implRecord.ImplRecordModel;
import com.hzhr.iot.device.sdk.service.Device_CollectDeviceService;
import com.hzhr.iot.device.sdk.service.Device_ImplRecordService;
import com.hzhr.iot.user.sdk.model.dept.DeptModel;
import com.hzhr.iot.user.sdk.model.dept_name.Dept_NameModel;
import com.hzhr.iot.user.sdk.service.User_DeptService;
import com.hzhr.iot.user.sdk.service.User_Dept_NameService;
import com.hzhr.iot.web.Global;
import com.hzhr.iot.web.controller.base.BaseController;
import com.hzhr.iot.web.model.response.BaseResponse;
import com.hzhr.iot.web.util.DeleteFileUtil;
import com.hzhr.iot.web.util.StringHelper;
import com.hzhr.iot.web.util.XwpfTUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.*;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

@RequestMapping("/dtuimplrecord")
@Api(description = "实施档案")
@RestController
public class DtuimplrecordController extends BaseController {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    Device_ImplRecordService device_implRecordService;

    @Autowired
    Device_CollectDeviceService device_collectDeviceService;

    @Autowired
    User_Dept_NameService user_dept_nameService;

    @Autowired
    User_DeptService user_deptService;

    @Value("${zipdown}")
    private String ZIPDOWN;

    @Autowired
    Global global;

    @Value("${replacePath}")
    String replacePath;

    @ApiOperation(value = "获取列表", notes = "获取列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pageNum", value = "当前页码",required = false, dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "pageSize", value = "单页面条数", required =false,dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "uat", value = "用户登录令牌", dataType = "String", required = true, paramType = "query"),
            @ApiImplicitParam(name = "recordNo", value = "记录编号", dataType = "int", required = false, paramType = "query"),
            @ApiImplicitParam(name = "begintime", value = "实施时间开始时间，形如2018-01-01 23:00:00", dataType = "String", required = false, paramType = "query"),
            @ApiImplicitParam(name = "endtime", value = "实施时间结束时间，形如2018-01-01 23:00:00", dataType = "String", required = false, paramType = "query"),
            @ApiImplicitParam(name = "gasUserNumber", value = "燃气用户编号", dataType = "String", required = false, paramType = "query"),
            @ApiImplicitParam(name = "gasUserName", value = "用户名称", required =false,dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "address", value = "地址", required =false,dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "coordinate", value = "坐标", required =false,dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "eqNo", value = "设备号", required =false,dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "dtuNo", value = "dtu编号", required =false,dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "sectionId", value = "所属分公司id", required =false,dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "managementId", value = "管理站id", required =false,dataType = "String", paramType = "query")
    })
    @RequestMapping(value = "/getlist", method = RequestMethod.POST)
    BaseResponse getlist(@RequestParam(value = "pageNum", required = false, defaultValue = "1") int pageNum,
                         @RequestParam(value = "pageSize", required = false, defaultValue = "1") int pageSize,
                         @RequestParam(value = "uat", required = true) String uat,
                         @RequestParam(value = "recordNo", required = false, defaultValue = "") String recordNo,
                         @RequestParam(value = "begintime", required = false, defaultValue = "") String begintime,
                         @RequestParam(value = "endtime", required = false, defaultValue = "") String endtime,
                         @RequestParam(value = "gasUserNumber", required = false, defaultValue = "") String gasUserNumber,
                         @RequestParam(value = "gasUserName", required = false, defaultValue = "") String gasUserName,
                         @RequestParam(value = "address", required = false, defaultValue = "") String address,
                         @RequestParam(value = "coordinate", required = false, defaultValue = "") String coordinate,
                         @RequestParam(value = "eqNo", required = false, defaultValue = "") String eqNo,
                         @RequestParam(value = "dtuNo", required = false, defaultValue = "") String dtuNo,
                         @RequestParam(value = "sectionId", required = false, defaultValue = "") String sectionId,
                         @RequestParam(value = "managementId", required = false, defaultValue = "") String managementId) throws Exception {
        Map<String, Object> result = new HashMap<String, Object>();
        List<Map<String, Object>> dataList = new ArrayList<Map<String, Object>>();
        result.put("dataList", dataList);

        Map<String, String> header = new HashMap<String, String>();
        header.put("token", this.global.getFirstToken());
        Map<String, Object> query = new HashMap<String, Object>();
        query.put("_show", "list");
        query.put("_show_info", Boolean.valueOf(true));
        query.put("_show_total", Boolean.valueOf(true));
        query.put("_page", Integer.valueOf(pageNum));
        query.put("_count", Integer.valueOf(pageSize));

        if (!StringUtils.isEmpty(recordNo)) {
            query.put("_equal_code", recordNo);
        }

        if (!StringUtils.isEmpty(eqNo)) {
            query.put("_like_collectDeviceCode", "%" + eqNo + "%");
        }

        if (!StringUtils.isEmpty(dtuNo)) {
            query.put("_like_iotDeviceCode", "%" + dtuNo + "%");
        }

        if (!StringUtils.isEmpty(gasUserNumber)) {
            query.put("_like_gasUserCode","%" +  gasUserNumber + "%");
        }

        if (!StringUtils.isEmpty(gasUserName)) {
            query.put("_like_gasUserName", "%" + gasUserName + "%");
        }

        if (!StringUtils.isEmpty(address)) {
            query.put("_like_gasUserAddress", "%" + address + "%");
        }

        if (!StringUtils.isEmpty(sectionId)) {
            Map<String, String> header1 = new HashMap<>();
            header1.put("token", global.getFirstToken());
            Map<String, Object> query1 = new HashMap<>();
            query1.put("equal_code", sectionId);
            query1.put("show", "one");
            DeptModel deptModel = user_deptService.get(header1, query1).getModel();
            if (deptModel != null) {
                query.put("_equal_subCompanyId", deptModel.getId());
            }
        }

        if(!StringHelper.isTrimEmpty(begintime)){
            SimpleDateFormat format =  new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            query.put("_greaterthanorequal_implementTime", String.valueOf(format.parse(begintime).getTime()));
        }
        if(!StringHelper.isTrimEmpty(endtime)){
            SimpleDateFormat format =  new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            query.put("_lessthanorequal_implementTime", String.valueOf(format.parse(endtime).getTime()));
        }

        ImplRecordGetModel implRecordGetModel = this.device_implRecordService.get1(header, query);
        Integer total = implRecordGetModel.getTotal();
        result.put("total", total);
        List<ImplRecordModel> implRecordModels = implRecordGetModel.getModelList();

        Iterator iterator = implRecordModels.iterator();
        while (iterator.hasNext()) {
            ImplRecordModel implRecordModel = (ImplRecordModel)iterator.next();
            Map<String, Object> item = new HashMap<String, Object>();

            item.put("id", implRecordModel.getId());
            item.put("recordNo", implRecordModel.getCode());
            item.put("gasUserName", implRecordModel.getGasUserName());
            item.put("address", implRecordModel.getGasUserAddress());
            item.put("gasUserNumber", implRecordModel.getGasUserCode());
            item.put("implementDate", implRecordModel.getImplementTime());
            Double longitude = implRecordModel.getLongitude();
            Double latitude = implRecordModel.getLatitude();
            if (longitude != null && latitude != null) {
                item.put("coordinate", longitude + " , " + latitude);
            }
            item.put("eqNo", implRecordModel.getCollectDeviceCode());
            item.put("dtuNo", implRecordModel.getIotDeviceCode());
            item.put("meterType", implRecordModel.getMeterType());
            Map<String, Object> implDtuprodfactory_prodFactoryId = new HashMap<String, Object>();
            implDtuprodfactory_prodFactoryId.put("des", implRecordModel.getProdFactoryDes());
            item.put("implDtuprodfactory_prodFactoryId", implDtuprodfactory_prodFactoryId);
            item.put("beforeReading", implRecordModel.getBeforeReading());
            item.put("afterReading", implRecordModel.getAfterReading());
            Map<String, Object> implDtuinstallfactory_installFactoryId = new HashMap<String, Object>();
            implDtuinstallfactory_installFactoryId.put("des", implRecordModel.getInstallFacotoryDes());
            item.put("implDtuinstallfactory_installFactoryId", implDtuinstallfactory_installFactoryId);
            Map<String, Object> implDtuiotequiptype_insEqTypeId = new HashMap<String, Object>();
            implDtuiotequiptype_insEqTypeId.put("des", implRecordModel.getIotDeviceTypeDes());
            item.put("implDtuiotequiptype_insEqTypeId", implDtuiotequiptype_insEqTypeId);
            item.put("simNo", implRecordModel.getSimNo());
            Map<String, Object> implMobileoperator_mobileOperatorId = new HashMap<String, Object>();
            implMobileoperator_mobileOperatorId.put("des", implRecordModel.getSimTypeDes());
            item.put("implMobileoperator_mobileOperatorId", implMobileoperator_mobileOperatorId);
            item.put("managedMeterCount", implRecordModel.getManagedMeterCount());
            Map<String, Object> implDtucollectionequiptype_managedMeterInfoId = new HashMap<String, Object>();
            implDtucollectionequiptype_managedMeterInfoId.put("des", implRecordModel.getManagedMeterInfoDes());
            item.put("implDtucollectionequiptype_managedMeterInfoId", implDtucollectionequiptype_managedMeterInfoId);
            Map<String, Object> implCommstatus_commStatusId = new HashMap<String, Object>();
            implCommstatus_commStatusId.put("des", implRecordModel.getCommStatusDes());
            item.put("implCommstatus_commStatusId", implCommstatus_commStatusId);
            Map<String, Object> implFixstatus_fixStatusId = new HashMap<String, Object>();
            implFixstatus_fixStatusId.put("des", implRecordModel.getFixStatusDes());
            item.put("implFixstatus_fixStatusId", implFixstatus_fixStatusId);
            Map<String, Object> implRunstatus_runStatusId = new HashMap<String, Object>();
            implRunstatus_runStatusId.put("des", implRecordModel.getRunStatusDes());
            item.put("implRunstatus_runStatusId", implRunstatus_runStatusId);
            item.put("voltage", implRecordModel.getAfterCellVoltage());
            item.put("implementer", implRecordModel.getImplementer());
            item.put("checker", implRecordModel.getChecker());
            item.put("implementation", "1、现场拍照（安装前环境）。\n2、安装固定物联网远传数据采集器。\n3、测试数据是否上传成功。\n4、数据上传成功后，现场拍照（安装后环境）。");

            String[] replacePathSplit = replacePath.split("--");
            String beforeImg = implRecordModel.getBeforeImg();
            String afterImg = implRecordModel.getAfterImg();
            String sceneImg = implRecordModel.getSceneImg();
            if (replacePathSplit.length == 2) {
                beforeImg = beforeImg.replace(replacePathSplit[0], replacePathSplit[1]);
                afterImg = afterImg.replace(replacePathSplit[0], replacePathSplit[1]);
                sceneImg = sceneImg.replace(replacePathSplit[0], replacePathSplit[1]);

            }
            item.put("beforeImg", beforeImg);
            item.put("afterImg", afterImg);
            item.put("sceneImg", sceneImg);

            dataList.add(item);
        }


        return new BaseResponse("0", "成功", result);
    }

    @ApiOperation(value = "获取Dtuimplrecord", notes = "获取Dtuimplrecord")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "eqNo", value = "设备号", required =true,dataType = "String", paramType = "query"),
    })
    @RequestMapping(value = "/getDtuimplrecord", method = RequestMethod.POST)
    BaseResponse getDtuimplrecord(@RequestParam(value ="eqNo", required = true,defaultValue = "0") String eqNo) throws Exception {
        List<Map<String, Object>> result = new ArrayList<Map<String, Object>>();

        Map<String, String> header = new HashMap<String, String>();
        header.put("token", this.global.getFirstToken());
        Map<String, Object> query = new HashMap<String, Object>();
        query.put("show", "list");
        query.put("show_info", Boolean.valueOf(true));
        query.put("show_collectDevice", Boolean.valueOf(true));
        query.put("show_iotDevice", Boolean.valueOf(true));
        query.put("show_gasUser", Boolean.valueOf(true));
        query.put("equal_collectDeviceCode", eqNo);
        List<ImplRecordModel> implRecordModels = this.device_implRecordService.get1(header, query).getModelList();
        if (implRecordModels != null && implRecordModels.size() > 0) {

            Iterator iterator = implRecordModels.iterator(); while (iterator.hasNext()) { ImplRecordModel implRecordModel = (ImplRecordModel)iterator.next();
                Map<String, Object> resultItem = new HashMap<String, Object>();

                resultItem.put("address", implRecordModel.getGasUserAddress());
                resultItem.put("eqNo", implRecordModel.getCollectDeviceCode());
                resultItem.put("dtuNo", implRecordModel.getIotDeviceCode());
                resultItem.put("gasUserNumber", implRecordModel.getGasUserCode());
                resultItem.put("gasUserName", implRecordModel.getGasUserName());

                String[] replacePathSplit = replacePath.split("--");
                String beforeImg = implRecordModel.getBeforeImg();
                String afterImg = implRecordModel.getAfterImg();
                String sceneImg = implRecordModel.getSceneImg();
                if (replacePathSplit.length == 2) {
                    beforeImg = beforeImg.replace(replacePathSplit[0], replacePathSplit[1]);
                    afterImg = afterImg.replace(replacePathSplit[0], replacePathSplit[1]);
                    sceneImg = sceneImg.replace(replacePathSplit[0], replacePathSplit[1]);

                }
                resultItem.put("beforeImg", beforeImg);
                resultItem.put("afterImg", afterImg);
                resultItem.put("sceneImg", sceneImg);

                resultItem.put("implDtuiotequiptype_insEqTypeId", implRecordModel.getIotDeviceTypeDes());
                Map<String, Object> userDept_sectionId = new HashMap<String, Object>();
                Map<String, Object> query1 = new HashMap<String, Object>();
                query1.put("_equal_id", implRecordModel.getSubCompanyId());
                query1.put("_show", "one");
                query1.put("_show_info", Boolean.valueOf(true));
                Dept_NameModel dept_nameModel = this.user_dept_nameService.get(header, query1).getModel();
                userDept_sectionId.put("name", (dept_nameModel != null) ? dept_nameModel.getName() : null);
                resultItem.put("userDept_sectionId", userDept_sectionId);
                Map<String, Object> userDept_managementId = new HashMap<String, Object>();
                query1.put("_equal_id", implRecordModel.getDeptId());
                dept_nameModel = this.user_dept_nameService.get(header, query1).getModel();
                userDept_managementId.put("name", (dept_nameModel != null) ? dept_nameModel.getName() : null);
                resultItem.put("userDept_managementId", userDept_managementId);

                result.add(resultItem); }

        }

        return new BaseResponse("0", "成功", result);
    }

    @ApiOperation(value = "导出实施档案", notes = "导出实施档案")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "uat", value = "用户登录令牌", dataType = "String", required = true, paramType = "query"),
            @ApiImplicitParam(name = "id", value = "记录编号", dataType = "String", required = true, paramType = "query")
    })
    @RequestMapping(value = "/expot", method = RequestMethod.GET)
    void expot(
            @RequestParam(value = "uat", required = true) String uat,
            @RequestParam(value = "id", required = true,defaultValue = "0") String id,
            HttpServletResponse response) throws Exception {
        Map<String, String> header = new HashMap<String, String>();
        header.put("token", this.global.getFirstToken());
        Map<String, Object> query = new HashMap<String, Object>();
        query.put("_show", "one");
        query.put("_show_info", Boolean.valueOf(true));
        query.put("_equal_id", id);
        ImplRecordGetModel implRecordGetModel = this.device_implRecordService.get1(header, query);

        ImplRecordModel implRecordModel= implRecordGetModel.getModel();
        Map<String,Object> params=new HashMap<>();
        SimpleDateFormat format =  new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        params.put("${recordNo}",implRecordModel.getCode());
        params.put("${userNO}",implRecordModel.getGasUserCode());
        params.put("${gasUserName}",implRecordModel.getGasUserName());
        params.put("${address}",implRecordModel.getGasUserAddress());
        Integer subCompanyId = implRecordModel.getSubCompanyId();
        if (subCompanyId != null) {
            Map<String, String> header1 = new HashMap<>();
            header1.put("token", global.getFirstToken());
            Map<String, Object> query1 = new HashMap<>();
            query1.put("_equal_id", subCompanyId);
            query1.put("_show", "one");
            query1.put("_show_info", true);
            Dept_NameModel dept_nameModel = user_dept_nameService.get(header1, query1).getModel();
            params.put("${sectionName}",dept_nameModel.getName());
        }
        params.put("${eqNo}", implRecordModel.getCollectDeviceCode());
        Integer deptId = implRecordModel.getDeptId();
        if (subCompanyId != null) {
            Map<String, String> header1 = new HashMap<>();
            header1.put("token", global.getFirstToken());
            Map<String, Object> query1 = new HashMap<>();
            query1.put("_equal_id", deptId);
            query1.put("_show", "one");
            query1.put("_show_info", true);
            Dept_NameModel dept_nameModel = user_dept_nameService.get(header1, query1).getModel();
            params.put("${managementName}",dept_nameModel.getName());
        }
        params.put("${meterType}", HzhrTypeUtil.object2string(implRecordModel.getMeterType()));
        params.put("${prodFactoryName}", HzhrTypeUtil.object2string(implRecordModel.getProdFactoryDes()));
        params.put("${beforeReading}", HzhrTypeUtil.object2string(implRecordModel.getBeforeReading()));
        params.put("${afterReading}", HzhrTypeUtil.object2string(implRecordModel.getAfterReading()));
        params.put("${insEqTypeName}", HzhrTypeUtil.object2string(implRecordModel.getIotDeviceTypeDes()));
        params.put("${installFactoryName}", HzhrTypeUtil.object2string(implRecordModel.getInstallFacotoryDes()));
        params.put("${simNo}", HzhrTypeUtil.object2string(implRecordModel.getSimNo()));
        params.put("${mobileOperatorName}", HzhrTypeUtil.object2string(implRecordModel.getSimTypeDes()));
        params.put("${managedMeterCount}",HzhrTypeUtil.object2string(implRecordModel.getManagedMeterCount()));
        params.put("${managedMeterInfoId}",HzhrTypeUtil.object2string(implRecordModel.getManagedMeterInfoDes()));
        params.put("${implementer}",HzhrTypeUtil.object2string(implRecordModel.getImplementer()));
        Long implementTime = implRecordModel.getImplementTime();
        if (implementTime != null) {
            params.put("${implementDate}", HzhrDateUtil.dateToStr(new Date(implementTime), "yyyy-MM-dd"));
        }
        params.put("${commStatusName}",HzhrTypeUtil.object2string(implRecordModel.getCommStatusDes()));
        params.put("${fixStatusName}",HzhrTypeUtil.object2string(implRecordModel.getFixStatusDes()));
        params.put("${voltage}",HzhrTypeUtil.object2string(implRecordModel.getAfterCellVoltage()));
        params.put("${runStatusName}",HzhrTypeUtil.object2string(implRecordModel.getRunStatusDes()));
        params.put("${checker}",HzhrTypeUtil.object2string(implRecordModel.getChecker()));
        Long checkTime = implRecordModel.getCheckTime();
        if (checkTime != null) {
            params.put("${checkDate}",HzhrDateUtil.dateToStr(new Date(checkTime), "yyyy-MM-dd"));
        }
        params.put("${implementation}","1、现场拍照（安装前环境）。\n2、安装固定物联网远传数据采集器。\n3、测试数据是否上传成功。\n4、数据上传成功后，现场拍照（安装后环境）。");
        params.put("id",HzhrTypeUtil.object2string(implRecordModel.getId()));

        Date dt=new Date();
        String dir=String.valueOf(dt.getTime());
        String outfile= CreateWord(params,dir+implRecordModel.getId());
        //图片
        String[] replacePathSplit = replacePath.split("--");
        if(implRecordModel.getBeforeImg()!=null) {
            String beforeImg = implRecordModel.getBeforeImg();
            if (replacePathSplit.length == 2) {
                beforeImg = beforeImg.replace(replacePathSplit[0], replacePathSplit[1]);
            }
            downloadPicture( str2list(beforeImg),ZIPDOWN+"downword/"+dir+implRecordModel.getId()+ URLEncoder.encode("/实施前图片/", "UTF-8"));
        }
        if(implRecordModel.getAfterImg()!=null) {
            String afterImg = implRecordModel.getAfterImg();
            if (replacePathSplit.length == 2) {
                afterImg = afterImg.replace(replacePathSplit[0], replacePathSplit[1]);
            }
            downloadPicture(str2list(afterImg),ZIPDOWN+"downword/"+dir+implRecordModel.getId()+URLEncoder.encode("/实施后图片/", "UTF-8"));

        }
        if(implRecordModel.getSceneImg()!=null) {
            String sceneImg = implRecordModel.getSceneImg();
            if (replacePathSplit.length == 2) {
                sceneImg = sceneImg.replace(replacePathSplit[0], replacePathSplit[1]);
            }
            downloadPicture(str2list(sceneImg),ZIPDOWN+"downword/"+dir+implRecordModel.getId()+URLEncoder.encode("/现场实施图片/", "UTF-8"));
        }

        List<String> list=new ArrayList<>();
        List<String> base=new ArrayList<>();
        list.add(outfile);
        base.add((implRecordModel.getGasUserCode()==null?"":implRecordModel.getGasUserCode()+"_"+(implRecordModel.getGasUserName()==null?"":implRecordModel.getGasUserName())+"_"+(implRecordModel.getCode()==null?"":implRecordModel.getCode())));
        outfile=CreateZip(dir,list,base);
        try {
            InputStream inStream = new FileInputStream(outfile);// 文件的存放路径
            // 设置输出的格式
            response.reset();
            response.setContentType("bin");
            Date date = new Date();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmm");
            response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(sdf.format(date),"UTF-8")  + ".zip");
            // 循环取出流中的数据
            byte[] b = new byte[100];
            int len;
            try {
                while ((len = inStream.read(b)) > 0)
                    response.getOutputStream().write(b, 0, len);
                inStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        try{
            DeleteFileUtil.deleteDir(new File(ZIPDOWN+"downword/"+dir+implRecordModel.getId()));
            DeleteFileUtil.deleteDir(new File(ZIPDOWN+"downzip/"+dir));
        }catch (Exception e){

        }


    }

    @ApiOperation(value = "批量导出实施档案", notes = "批量导出实施档案")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "uat", value = "用户登录令牌", dataType = "String", required = true, paramType = "query"),
            @ApiImplicitParam(name = "recordNo", value = "记录编号", dataType = "int", required = false, paramType = "query"),
            @ApiImplicitParam(name = "begintime", value = "实施时间开始时间，形如2018-01-01 23:00:00", dataType = "String", required = false, paramType = "query"),
            @ApiImplicitParam(name = "endtime", value = "实施时间结束时间，形如2018-01-01 23:00:00", dataType = "String", required = false, paramType = "query"),
            @ApiImplicitParam(name = "gasUserNumber", value = "燃气用户编号", dataType = "String", required = false, paramType = "query"),
            @ApiImplicitParam(name = "gasUserName", value = "用户名称", required =false,dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "address", value = "地址", required =false,dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "coordinate", value = "坐标", required =false,dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "eqNo", value = "设备号", required =false,dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "dtuNo", value = "dtu编号", required =false,dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "sectionId", value = "所属分公司id", required =false,dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "managementId", value = "管理站id", required =false,dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "recordNos", value = "记录编号逗号分隔", required =false,dataType = "String", paramType = "query")
    })
    @RequestMapping(value = "/expotall", method = RequestMethod.GET)
    void expotall(
            @RequestParam(value = "uat", required = true) String uat,
            @RequestParam(value = "recordNo", required = false,defaultValue = "") String recordNo,
            @RequestParam(value = "begintime", required = false,defaultValue = "") String begintime,
            @RequestParam(value = "endtime", required = false,defaultValue = "") String endtime,
            @RequestParam(value = "gasUserNumber", required = false,defaultValue = "") String gasUserNumber,
            @RequestParam(value = "gasUserName", required = false,defaultValue = "") String gasUserName,
            @RequestParam(value = "address", required = false,defaultValue = "") String address,
            @RequestParam(value = "coordinate", required = false,defaultValue = "") String coordinate,
            @RequestParam(value = "eqNo", required = false,defaultValue = "") String eqNo,
            @RequestParam(value = "dtuNo", required = false,defaultValue = "") String dtuNo,
            @RequestParam(value = "sectionId", required = false,defaultValue = "") String sectionId,
            @RequestParam(value = "managementId", required = false,defaultValue = "") String managementId,
            @RequestParam(value = "recordNos", required = false,defaultValue = "") String recordNos,
            HttpServletResponse response) throws Exception {
        Map<String, String> header = new HashMap<String, String>();
        header.put("token", this.global.getFirstToken());
        Map<String, Object> query = new HashMap<String, Object>();
        query.put("_show", "list");
        query.put("_show_info", true);
        query.put("_show_total", true);
        query.put("_page", 1);
        query.put("_count", 99999);

        if(!StringHelper.isTrimEmpty(recordNos)) {
            query.put("_in_code", recordNos);
        } else {
            if (!StringUtils.isEmpty(recordNo)) {
                query.put("_equal_code", recordNo);
            }

            if (!StringUtils.isEmpty(eqNo)) {
                query.put("_equal_collectDeviceCode", eqNo);
            }

            if (!StringUtils.isEmpty(dtuNo)) {
                query.put("_equal_iotDeviceCode", dtuNo);
            }

            if (!StringUtils.isEmpty(gasUserNumber)) {
                query.put("_equal_gasUserCode", gasUserNumber);
            }

            if (!StringUtils.isEmpty(gasUserName)) {
                query.put("_like_gasUserName", "%" + gasUserName + "%");
            }

            if (!StringUtils.isEmpty(address)) {
                query.put("_like_gasUserAddress", "%" + address + "%");
            }

            if (!StringUtils.isEmpty(sectionId)) {
                Map<String, String> header1 = new HashMap<>();
                header1.put("token", global.getFirstToken());
                Map<String, Object> query1 = new HashMap<>();
                query1.put("equal_code", sectionId);
                query1.put("show", "one");
                DeptModel deptModel = user_deptService.get(header1, query1).getModel();
                if (deptModel != null) {
                    query.put("_equal_subCompanyId", deptModel.getId());
                }
            }


            if(!StringHelper.isTrimEmpty(begintime)){
                SimpleDateFormat format =  new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                query.put("_greaterthanorequal_implementTime", String.valueOf(format.parse(begintime).getTime()));
            }
            if(!StringHelper.isTrimEmpty(endtime)){
                SimpleDateFormat format =  new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                query.put("_lessthanorequal_implementTime", String.valueOf(format.parse(endtime).getTime()));
            }
        }

        ImplRecordGetModel implRecordGetModel = this.device_implRecordService.get1(header, query);

        Date dt=new Date();
        String dir=String.valueOf(dt.getTime());
        List<String> list=new ArrayList<>();
        List<String> base=new ArrayList<>();
        List<String> deletefile=new ArrayList<>();
        if(implRecordGetModel.getTotal()!=null&&implRecordGetModel.getTotal()>0&&implRecordGetModel.getModelList().size()>0){
            Map<String,Object> params=new HashMap<>();
            for (int i=0;i<implRecordGetModel.getModelList().size();i++){
                params.clear();
                ImplRecordModel implRecordModel= implRecordGetModel.getModelList().get(i);
                SimpleDateFormat format =  new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                params.put("${recordNo}",implRecordModel.getCode());
                params.put("${userNO}",implRecordModel.getGasUserCode());
                params.put("${gasUserName}",implRecordModel.getGasUserName());
                params.put("${address}",implRecordModel.getGasUserAddress());
                Integer subCompanyId = implRecordModel.getSubCompanyId();
                if (subCompanyId != null) {
                    Map<String, String> header1 = new HashMap<>();
                    header1.put("token", global.getFirstToken());
                    Map<String, Object> query1 = new HashMap<>();
                    query1.put("_equal_id", subCompanyId);
                    query1.put("_show", "one");
                    query1.put("_show_info", true);
                    Dept_NameModel dept_nameModel = user_dept_nameService.get(header1, query1).getModel();
                    params.put("${sectionName}",dept_nameModel.getName());
                }
                params.put("${eqNo}", implRecordModel.getCollectDeviceCode());
                Integer deptId = implRecordModel.getDeptId();
                if (subCompanyId != null) {
                    Map<String, String> header1 = new HashMap<>();
                    header1.put("token", global.getFirstToken());
                    Map<String, Object> query1 = new HashMap<>();
                    query1.put("_equal_id", deptId);
                    query1.put("_show", "one");
                    query1.put("_show_info", true);
                    Dept_NameModel dept_nameModel = user_dept_nameService.get(header1, query1).getModel();
                    params.put("${managementName}",dept_nameModel.getName());
                }
                params.put("${meterType}", HzhrTypeUtil.object2string(implRecordModel.getMeterType()));
                params.put("${prodFactoryName}", HzhrTypeUtil.object2string(implRecordModel.getProdFactoryDes()));
                params.put("${beforeReading}", HzhrTypeUtil.object2string(implRecordModel.getBeforeReading()));
                params.put("${afterReading}", HzhrTypeUtil.object2string(implRecordModel.getAfterReading()));
                params.put("${insEqTypeName}", HzhrTypeUtil.object2string(implRecordModel.getIotDeviceTypeDes()));
                params.put("${installFactoryName}", HzhrTypeUtil.object2string(implRecordModel.getInstallFacotoryDes()));
                params.put("${simNo}", HzhrTypeUtil.object2string(implRecordModel.getSimNo()));
                params.put("${mobileOperatorName}", HzhrTypeUtil.object2string(implRecordModel.getSimTypeDes()));
                params.put("${managedMeterCount}",HzhrTypeUtil.object2string(implRecordModel.getManagedMeterCount()));
                params.put("${managedMeterInfoId}",HzhrTypeUtil.object2string(implRecordModel.getManagedMeterInfoDes()));
                params.put("${implementer}",HzhrTypeUtil.object2string(implRecordModel.getImplementer()));
                Long implementTime = implRecordModel.getImplementTime();
                if (implementTime != null) {
                    params.put("${implementDate}", HzhrDateUtil.dateToStr(new Date(implementTime), "yyyy-MM-dd"));
                }
                params.put("${commStatusName}",HzhrTypeUtil.object2string(implRecordModel.getCommStatusDes()));
                params.put("${fixStatusName}",HzhrTypeUtil.object2string(implRecordModel.getFixStatusDes()));
                params.put("${voltage}",HzhrTypeUtil.object2string(implRecordModel.getAfterCellVoltage()));
                params.put("${runStatusName}",HzhrTypeUtil.object2string(implRecordModel.getRunStatusDes()));
                params.put("${checker}",HzhrTypeUtil.object2string(implRecordModel.getChecker()));
                Long checkTime = implRecordModel.getCheckTime();
                if (checkTime != null) {
                    params.put("${checkDate}",HzhrDateUtil.dateToStr(new Date(checkTime), "yyyy-MM-dd"));
                }
                params.put("${implementation}","1、现场拍照（安装前环境）。\n2、安装固定物联网远传数据采集器。\n3、测试数据是否上传成功。\n4、数据上传成功后，现场拍照（安装后环境）。");
                params.put("id",HzhrTypeUtil.object2string(implRecordModel.getId()));
                String outfile= CreateWord(params,dir+implRecordModel.getId());
                try{
                    //图片
                    String[] replacePathSplit = replacePath.split("--");
                    if(implRecordModel.getBeforeImg()!=null) {
                        String beforeImg = implRecordModel.getBeforeImg();
                        if (replacePathSplit.length == 2) {
                            beforeImg = beforeImg.replace(replacePathSplit[0], replacePathSplit[1]);
                        }
                        downloadPicture( str2list(beforeImg),ZIPDOWN+"downword/"+dir+implRecordModel.getId()+ URLEncoder.encode("/实施前图片/", "UTF-8"));
                    }
                    if(implRecordModel.getAfterImg()!=null) {
                        String afterImg = implRecordModel.getAfterImg();
                        if (replacePathSplit.length == 2) {
                            afterImg = afterImg.replace(replacePathSplit[0], replacePathSplit[1]);
                        }
                        downloadPicture(str2list(afterImg),ZIPDOWN+"downword/"+dir+implRecordModel.getId()+URLEncoder.encode("/实施后图片/", "UTF-8"));

                    }
                    if(implRecordModel.getSceneImg()!=null) {
                        String sceneImg = implRecordModel.getSceneImg();
                        if (replacePathSplit.length == 2) {
                            sceneImg = sceneImg.replace(replacePathSplit[0], replacePathSplit[1]);
                        }
                        downloadPicture(str2list(sceneImg),ZIPDOWN+"downword/"+dir+implRecordModel.getId()+URLEncoder.encode("/现场实施图片/", "UTF-8"));
                    }
                }catch (IOException e){
                    logger.info("下载图片失败");
                }
                deletefile.add(ZIPDOWN+"downword/"+dir+implRecordModel.getId());
                list.add(outfile);
                base.add((implRecordModel.getGasUserCode()==null?"":implRecordModel.getGasUserCode()+"_"+(implRecordModel.getGasUserName()==null?"":implRecordModel.getGasUserName())+"_"+(implRecordModel.getCode()==null?"":implRecordModel.getCode())));
            }
        }

        String outputUrl= CreateZip(dir,list,base);
        try {
            InputStream inStream = new FileInputStream(outputUrl);// 文件的存放路径
            // 设置输出的格式
            response.reset();
            response.setContentType("bin");
            Date date = new Date();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmm");
            response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(sdf.format(date),"UTF-8")  + ".zip");
            // 循环取出流中的数据
            byte[] b = new byte[100];
            int len;
            try {
                while ((len = inStream.read(b)) > 0)
                    response.getOutputStream().write(b, 0, len);
                inStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        try{
            for (String item:deletefile) {
                DeleteFileUtil.deleteDir(new File(item));
            }
            DeleteFileUtil.deleteDir(new File(ZIPDOWN+"downzip/"+dir));
        }catch (Exception e){

        }
    }

    private String CreateZip(String dir, List<String> list, List<String> basedir) throws IOException {
        String outputUrl= URLDecoder.decode(ZIPDOWN+"downzip/"+dir, "UTF-8");
        File zip = new File(outputUrl);
        if (!zip.exists()){
            zip.mkdirs();
        }
        File zipfile = new File(URLDecoder.decode(outputUrl+"/down.zip","UTF-8"));
        //创建zip文件输出流
        FileOutputStream fos = new FileOutputStream(zipfile);
        long start = System.currentTimeMillis();
        ZipOutputStream zos = null ;
        try {
            zos = new ZipOutputStream(fos);
            BufferedOutputStream bos = new BufferedOutputStream(zos);
            for (int i=0;i<list.size();i++){
                File srcFile=new File(list.get(i));
//                if(srcFile.isDirectory())
//                {
//                    File[] flist = srcFile.listFiles();
//
//                    if(flist.length>0)
//                    {
//                        String basepath= srcFile.getPath().substring(srcFile.getPath().lastIndexOf('\\')+1);
//                        zos.putNextEntry(new ZipEntry(basepath+"/"));
//                        for(int i=0;i<flist.length;i++)
//                        {
//                            byte[] buf = new byte[BUFFER_SIZE];
//                            zos.putNextEntry(new ZipEntry(basepath+"/"+flist[i].getName()));
//                            int len;
//                            FileInputStream in = new FileInputStream(flist[i]);
//                            while ((len = in.read(buf)) != -1){
//                                zos.write(buf, 0, len);
//                            }
//                            zos.closeEntry();
//                            in.close();
//                        }
//                    }
//                }
//                String basepath= srcFile.getPath().substring(srcFile.getPath().lastIndexOf('\\')+1);
                try {
                    compress(zos, bos, srcFile, basedir.get(i));
                } catch (Exception e) {
                    throw new RuntimeException("zip error from ZipUtils2",e);
                }

            }
            long end = System.currentTimeMillis();
            // 读到流中

        } catch (Exception e) {
            throw new RuntimeException("zip error from ZipUtils",e);
        }finally{
            zos.close();
            fos.close();
        }
        return zipfile.getPath();
    }

    public void compress(ZipOutputStream out, BufferedOutputStream bos,File sourceFile,String base) throws Exception
    {

        //如果路径为目录（文件夹）
        if(sourceFile.isDirectory())
        {
            //取出文件夹中的文件（或子文件夹）
            File[] flist = sourceFile.listFiles();

            if(flist.length==0)//如果文件夹为空，则只需在目的地zip文件中写入一个目录进入点
            {
                out.putNextEntry(  new ZipEntry(base+"/") );
            }
            else//如果文件夹不为空，则递归调用compress，文件夹中的每一个文件（或文件夹）进行压缩
            {
                for(int i=0;i<flist.length;i++)
                {
                    compress(out,bos,flist[i],base+"/"+flist[i].getName());
                }
            }
        }
        else//如果不是目录（文件夹），即为文件，则先写入目录进入点，之后将文件写入zip文件中
        {

            out.putNextEntry( new ZipEntry(base) );
            FileInputStream fos = new FileInputStream(sourceFile);
            BufferedInputStream bis = new BufferedInputStream(fos);
            try{
                int tag;
                while((tag=bis.read())!=-1)
                {
                    out.write(tag);
                }
            }catch (Exception e){
                throw new RuntimeException("zip error from ZipUtils1",e);
            }finally{
                bis.close();
                fos.close();
            }
        }


    }

    private String CreateWord(Map<String, Object> params,String dir) throws IOException {

        String templatePath = ZIPDOWN+"ftl/实施档案.docx";
        XwpfTUtil xwpfTUtil = new XwpfTUtil();

        XWPFDocument doc;
        InputStream is;
        is = new FileInputStream(URLDecoder.decode(templatePath, "UTF-8"));
        doc = new XWPFDocument(is);

        xwpfTUtil.replaceInPara(doc, params);
        //替换表格里面的变量
        xwpfTUtil.replaceInTable(doc, params);

        File file = new File(URLDecoder.decode(ZIPDOWN+"downword/"+dir, "UTF-8"));
        if(!file.exists()) {
            file.mkdirs();
        }
        String filepath=URLDecoder.decode(ZIPDOWN+"downword/"+dir+"/实施档案.docx", "UTF-8");
        File outfile = new File(filepath);
        FileOutputStream stream = new FileOutputStream(outfile);
        doc.write(stream);
        xwpfTUtil.close(is);
        stream.close();

        return URLDecoder.decode(ZIPDOWN+"downword/"+dir+"/", "UTF-8");
    }

    //链接url下载图片
    private void downloadPicture(List<String> urlList, String path) throws UnsupportedEncodingException {
        URL url = null;
        File file = new File(URLDecoder.decode(path, "UTF-8"));
        if(!file.exists()) {
            file.mkdirs();
        }
        try {
            for (int i=0;i<urlList.size();i++){
                String urlpath=urlList.get(i);

                if (StringUtils.isEmpty(urlpath)) continue;

                String imageName=URLDecoder.decode(path+urlpath.substring(urlpath.lastIndexOf('/')+1), "UTF-8");
                url = new URL(URLDecoder.decode(urlpath, "UTF-8"));
                URLConnection uc = url.openConnection();
                DataInputStream dataInputStream = new DataInputStream(url.openStream());

                FileOutputStream fileOutputStream = new FileOutputStream(new File(imageName));
                ByteArrayOutputStream output = new ByteArrayOutputStream();

                byte[] buffer = new byte[1024];
                int length;

                while ((length = dataInputStream.read(buffer)) > 0) {
                    output.write(buffer, 0, length);
                }
                byte[] context=output.toByteArray();
                fileOutputStream.write(output.toByteArray());
                dataInputStream.close();
                fileOutputStream.close();
            }

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private List<String> str2list(String str) {
        str = str.replace("[", "").replace("]", "").replace("\"", "");
        String[] strs = str.split(",");
        List<String> result = new ArrayList<>();
        for (String item :
                strs) {
            result.add(item);
        }
        return result;
    }

}
